package com.ifdom.thread.multthread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * @author dell
 * @date 2022/06/28
 */
public final class ThreadThirdPool {
    private volatile static ThreadPoolExecutor executor;

    private ThreadThirdPool() {
    }

    public static ExecutorService getExecutorService() {
        if (executor == null) {
            synchronized (ThreadThirdPool.class) {
                if (executor == null) {
                    executor = new ThreadPoolExecutor(1, 5, 30, TimeUnit.SECONDS,
                            new LinkedBlockingQueue<>(5),
                            new CustomThreadFactory("自定义线程"),
                            new ThreadPoolExecutor.AbortPolicy());
                }
            }
        }
        return executor;
    }

    private static class CustomThreadFactory implements ThreadFactory {

        private final ThreadGroup threadGroup;

        private final AtomicInteger threadNumber = new AtomicInteger();

        private final String namePrefix;

        private CustomThreadFactory(String name) {
            SecurityManager securityManager = System.getSecurityManager();
            threadGroup = (securityManager != null) ? securityManager.getThreadGroup()
                    : Thread.currentThread().getThreadGroup();

            if (null == name || "".equals(name.trim())) {
                name = "pool";
            }

            AtomicInteger poolNumber = new AtomicInteger(1);
            namePrefix = name + "-" + poolNumber.getAndIncrement() + "-thread";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(threadGroup, r, namePrefix + threadNumber.getAndIncrement(), 0);

            if (thread.isDaemon()) {
                thread.setDaemon(false);
            }

            if (thread.getPriority() != Thread.NORM_PRIORITY) {
                thread.setPriority(Thread.NORM_PRIORITY);
            }
            return thread;
        }
    }
}
